<?php

/**
 *
 * 
 */
class CategoryController extends MainController implements ControllerInterface {

	/**
	 * Strona glowna
	 *
	 */
	private static $_mainLanguageId = 1;

	public function IndexAction($param) {

		$table_data = $this->getTableData('category_table', $param, array('o' => 'name', 'v' => 'malejaco', 't' => 10));
		$v = $table_data['v'] == 'malejaco' ? 'DESC' : 'ASC';
		$oTable = array(
			'name' => 'category_description.name',
			'description' => 'category_description.description',
			'status' => 'category.active'
		);
		$o = $oTable[$table_data['o']];
		$p = isset($param['strona']) ? $param['strona'] : 1;

		$dalData = CategoryDAL::GetDalDataObj(
						array(
							'count' => true,
							'condition' => array(
							//'parent'=> array('NULL'),
							),
							'join' => array(
								'CategoryDescription' => ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = ' . Registry::Get('APPLICATION_LANGUAGE_ID') . ')',
							),
						)
		);
		$this->smarty->assign('c', CategoryDAL::getResult($dalData));

		$dalData->setSortBy("$o $v");
		$dalData->setCount(false);
		$dalData->setLimit((($p - 1) * $table_data['t']) . ', ' . $table_data['t']);



		$arrayObjCategories = CategoryDAL::GetResult($dalData);


		$this->smarty->assign('arrayObjCategories', $arrayObjCategories);
	}

	public function StructureAction($param) {
		$table_data = $this->getTableData('category_table', $param, array('o' => 'name', 'v' => 'malejaco', 't' => 20));
		$v = $table_data['v'] == 'malejaco' ? 'DESC' : 'ASC';
		$oTable = array(
			'name' => 'category_description.name',
				//'description' => 'category_description.description',
			'status' => 'category.active'
		);
		$o = $oTable[$table_data['o']];
		$p = isset($param['strona']) ? $param['strona'] : 1;

		$dalData = CategoryDAL::GetDalDataObj(
						array(
							'count' => true,
							'condition' => array(
							//'parent'=> array('NULL'),
							),
							'join' => array(
								'CategoryDescription' => ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = 1)',
							),
						)
		);
		$this->smarty->assign('c', CategoryDAL::getResult($dalData));

		$dalData->setCount(false);
		$dalData->setLimit((($p - 1) * $table_data['t']) . ', ' . $table_data['t']);

//		$dalData->setOrderBy('category_description ASC');

		$arrayObjCategories = CategoryDAL::GetResult($dalData);


		$this->smarty->assign('arrayObjCategories', $arrayObjCategories);
	}

	/**
	 * Nowa kategoria/branża
	 *
	 */
	public function AddAction() {

		$obj = new Category();
		$obj->loadAdminDescription();

		$languages = LanguageDAL::GetResult(LanguageDAL::GetDalDataObj());
		$_languages = array();
		foreach ($languages as $lang) {
			$_languages[$lang->getId()] = $lang;
		}

		if (Request::IsPost()) {

			$errorsList = $this->ValidateAddCategory();
			if (empty($errorsList)) {
				// upload obrazków

				$obj->setSlug(uniqid());
				$obj->setActive(Request::Get('active'));
				$obj->setParent((Request::Get('parent') > 0 ? Request::Get('parent') : 0));
				$obj->setGuide(0);
				$obj->setProductsCount(0);
				$obj->setImage('');
				$obj->setDate('2011-01-01 00:00:01');

				$obj->setId(CategoryDAL::Save($obj->GetDalDataObj()));
				$imgName = '';
				// wersje językowe
				foreach ($_languages as $lang) {
					$ld = Request::Get($lang->getCode());
					$desc = new CategoryDescription();
					$desc->setName(isset($ld['name']) ? $ld['name'] : 'none');
					$desc->setDescription(isset($ld['description']) ? $ld['description'] : '');
					$desc->setSeoKeywords(isset($ld['seo_keywords']) ? $ld['seo_keywords'] : '');
					$desc->setSeoDescription(isset($ld['seo_description']) ? $ld['seo_description'] : '');
					$desc->setIdCategory($obj->getId());
					$desc->setIdLanguage($lang->getId());

					CategoryDescriptionDAL::Save($desc->GetDalDataObj());

					if ($lang->getId() == self::$_mainLanguageId) {
						$_sl = Request::Get('slug');
						$imgName = $desc->getName();
						$slugTxt = empty($_sl) ? (($desc->getName() == 'none') ? uniqueid() : $desc->getName()) : $_sl;
					}
				}
				$imgPath = '';
				if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK && $imgName) {
					$imgName = Utils::TextToUrl($imgName) . '.' . array_pop(explode('.', $_FILES['image']['name']));
					$imgPath = CategoryDAL::$imageDir . $imgName;
					if (!move_uploaded_file($_FILES['image']['tmp_name'], PATH_STATIC_CONTENT . $imgPath)) {
						$imgPath = '';
					}
				}
				$obj->setSlug(CategoryDAL::GenerateUniqueSlug($slugTxt));
				$obj->setImage($imgPath);


				$insertId = CategoryDAL::Save($obj->GetDalDataObj());

				return $this->AddRedirect(Router::GenerateUrl('CategoryEdit', array('Category' => 'Index')), 0);
			} else {
				$this->smarty->assign('error', $errorsList);
			}
		}
		$this->smarty->assign('obj', $obj);
		// jezyki

		$this->smarty->assign('languages', $_languages);
		// kategorie nadrzędne

		$this->smarty->assign('mainCategories', CategoryDAL::GetResult(
						CategoryDAL::GetDalDataObj(
								array(
									'condition' => array(
										'parent' => array('0'),
									),
									'join' => array(
										'CategoryDescription' => ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = 1)'
									)
								)
						)
				));
	}

	private function ValidateAddCategory() {
		$errors = array();

		$data = Request::GetAllPost();
		$languages = LanguageDAL::GetResult(LanguageDAL::GetDalDataObj());
		// walidacja języków
		foreach ($languages as $lang) {
			$validator = new Validator($data[$lang->getCode()]);
			$validator->IsEmpty('name', 'Pole "Nazwa" nie może być puste.');
			$validator->IsEmpty('description', 'Pole "Opis" nie może być puste.');
			$errors[$lang->getCode()] = $validator->GetErrorList();
			unset($data[$lang->getCode()]);
		}
		// walidacja całej reszty
		$validator = new Validator($data);
		$validator->IsEmpty('slug', 'Pole "URL" nie może być puste.');
		$validator->IsEmpty('active', 'Pole "Aktywny" nie może być puste.');


		return array();
		return $errors;
	}

	public function AjaxSlugifyAction($param) {
		
	}

	/**
	 * Edycja Category'u
	 *
	 * @param array $param
	 */
	public function EditAction($param) {


		$obj = CategoryDAL::GetResult(
						CategoryDAL::GetDalDataObj(
								array(
									'condition' => array(
										'id' => array($param['id'])
									)
								)
						)
		);

		$obj = $obj[0];

		$languages = LanguageDAL::GetResult(LanguageDAL::GetDalDataObj());
		$_languages = array();
		foreach ($languages as $lang) {
			$_languages[$lang->getId()] = $lang;
		}



		if (Request::IsPost()) {
			$errorsList = array();
			//$errorsList = $this->ValidateAddCategory(); 

			if (empty($errorsList)) {
				//
				$obj->setActive(Request::Get('active'));
				$obj->setParent((Request::Get('parent') > 0 ? Request::Get('parent') : 0));
				$obj->setGuide(0);
				$obj->setProductsCount(0);
				$obj->setImage('');
				$obj->setDate('2011-01-01 00:00:01');

				CategoryDAL::Save($obj->GetDalDataObj());

				$imgName = '';
				$slugTxt = '';
				// wersje językowe

				$descObjArr = CategoryDescriptionDAL::GetResult(
								CategoryDescriptionDAL::GetDalDataObj(
										array(
											'condition' => array('id_category' => array($obj->getId()))
										)
								)
				);

				$_descObjArr = array();

				foreach ($descObjArr as $desc) {
					$_descObjArr[$desc->getIdLanguage()] = $desc;
				}

				foreach ($_languages as $lang) {

					$ld = Request::Get($lang->getCode());
					if (in_array($lang->getId(), array_keys($_descObjArr))) {


						$_d = $_descObjArr[$lang->getId()];
						$_d->setName($ld['name']);
						$_d->setDescription($ld['description']);
						$_d->setSeoKeywords($ld['seo_keywords']);
						$_d->setSeoDescription($ld['seo_description']);
						$_d->setIdCategory($obj->getId());
						$_d->setIdLanguage($lang->getId());

						CategoryDescriptionDAL::Save($_d->GetDalDataObj());
					} else {
						$_d = new CategoryDescription();
						$_d->setName($ld['name']);
						$_d->setDescription($ld['description']);
						$_d->setSeoKeywords($ld['seo_keywords']);
						$_d->setSeoDescription($ld['seo_description']);
						$_d->setIdCategory($obj->getId());
						$_d->setIdLanguage($lang->getId());

						CategoryDescriptionDAL::Save($_d->GetDalDataObj());
					}

					if ($lang->getId() == self::$_mainLanguageId) {
						$_sl = Request::Get('slug');
						$imgName = $_d->getName();
						$slugTxt = empty($_sl) ? $_d->getName() : $_sl;
					}
				}


				if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
					$imgName = Utils::TextToUrl($imgName) . '.' . array_pop(explode('.', $_FILES['image']['name']));
					$imgPath = CategoryDAL::$imageDir . $imgName;
					if (!move_uploaded_file($_FILES['image']['tmp_name'], PATH_STATIC_CONTENT . $imgPath)) {
						$imgPath = '';
					}
					$obj->setImage($imgPath);
				}
				if ($slugTxt != $obj->getSlug())
					$obj->setSlug(CategoryDAL::GenerateUniqueSlug($slugTxt));
				CategoryDAL::Save($obj->GetDalDataObj());

				return $this->AddRedirect(Router::GenerateUrl('CategoryEdit', array('Category' => 'Index')), 0);
			} else {
				$this->smarty->assign('error', $errorsList);
			}
		}

		$this->smarty->assign('obj', $obj);

		$this->smarty->assign('languages', $_languages);
		// kategorie nadrzędne
		$this->smarty->assign('mainCategories', CategoryDAL::GetResult(
						CategoryDAL::GetDalDataObj(
								array(
									'condition' => array(
										'parent' => array('0'),
										'category.id_category' => array(array('condition' => '!=', 'value' => $obj->getId()))
									),
									'join' => array(
										'CategoryDescription' => ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = 1)'
									)
								)
						)
				));
	}

	/**
	 *  Oceny czastkowe
	 * @param type $param 
	 */
	public function VoteIndexAction($param) {
		if (empty($param['id']))
			return $this->AddRedirect(Router::GenerateUrl('LanguageIndex', array('Category' => 'Index')), 0);

		//podkategoria
		$obj = CategoryDAL::GetResult(
						CategoryDAL::GetDalDataObj(
								array(
									'condition' => array(
										'id' => array($param['id'])
									)
								)
						)
		);
		$obj = $obj[0];
		$sub_category = $obj->getAdminDescriptions();
		$sub_category = array_shift($sub_category);

		//kategoria (parent)
		$obj = CategoryDAL::GetResult(
						CategoryDAL::GetDalDataObj(
								array(
									'condition' => array(
										'id' => array($obj->getParent())
									)
								)
						)
		);

		$obj = $obj[0];
		$category = $obj->getAdminDescriptions();
		$category = array_shift($category);
		$list = $this->getVoteList($param);

		$arrData = array(
			'id' => $param['id'],
			'vid' => isset($param['vid']) ? $param['vid'] : -1,
			'category' => $category->getName(),
			'subCategory' => $sub_category->getName());

		if (isset($param['vid']))
			$arrData['vname'] = $list[$param['vid']]->getName();

		$this->smarty->assign('arrData', $arrData);
		$this->smarty->assign('list', $list);
	}

	public function VoteEditAction($param) {
		if(isset($param['vid']))
			$settings = array(
					'condition' => array(
					'id_product_votes_type' => array($param['vid'])));
		else
			$settings = array();
		
		$dalObj = ProductVotesTypeDAL::GetDalDataObj($settings);
		$vote = ProductVotesTypeDAL::GetResult($dalObj);
		$vote = $vote[0];

		if (Request::IsPost() && Request::Get('go')) {
			$errorsList = array();
			if (empty($errorsList)) {
				if(!empty($param['id']))
					$id = $param['id'];
				else
					$id = '';

				//zapis do bazy
				$this->processEditVote($param);

				$info = 'Zmiany zostały zachowane';
				$this->AddRedirectInfo($info, true, Router::GenerateUrl('CategoryVoteIndex', array('Category' => 'VoteIndex', 'id' => $id)), 0);
			} else {
				$this->smarty->assign('error', $errorsList);
			}
		}
		
		$arrData = array(
			'id' => isset($param['id']) ? $param['id'] : '' ,
			'vid' => isset($param['vid']) ? $param['vid'] : -1,
			'title' => isset($param['vid']) ? 'Dane ogólne' : 'Utwórz nową',
			'title_main' => isset($param['vid']) ? 'Edytujesz ocenę cząstkową' : 'Dodajesz nową ocenę cząstkową');

		if (isset($param['vid'])) {
			$arrData['vname'] = $vote->getName();
			$arrData['overall'] = $vote->getOverall();
			$arrData['active'] = $vote->getActive();
		}

		$this->smarty->assign('arrData', $arrData);
	}
	private function getVoteList($param, $all = false) {

		$table_data = $this->getTableData('category_table', $param, array('o' => 'name', 'v' => 'malejaco', 't' => 10));
		$v = $table_data['v'] == 'malejaco' ? 'DESC' : 'ASC';
		$oTable = array(
			'name' => 'category_description.name',
			'description' => 'category_description.description'
		);
		$o = $oTable[$table_data['o']];
		$p = isset($param['strona']) ? $param['strona'] : 1;
		
		$settings = array();

		if (!$all) {
			$settings = array(
					'condition' => array(
					'id_category' => array(isset($param['cat_id']) ? $param['cat_id'] : (isset($param['id']) ? $param['id'] : null)) 
					));
		}
		$dalData = ProductVotesTypeDAL::GetDalDataObj($settings);
		$dalData->setLimit((($p - 1) * $table_data['t']) . ', ' . $table_data['t']);
		$obj = ProductVotesTypeDAL::GetResult($dalData);

		$tmp = array();
		foreach ($obj as $item) {
			$tmp[$item->getId()] = $item;
		}
		
		return $tmp;
	}
	private function getVoteListCount($param) {
		$table_data = $this->getTableData('category_table', $param, array('o' => 'name', 'v' => 'malejaco', 't' => 10));
		$v = $table_data['v'] == 'malejaco' ? 'DESC' : 'ASC';
		$oTable = array(
			'name' => 'category_description.name',
			'description' => 'category_description.description'
		);
		$o = $oTable[$table_data['o']];
		$p = isset($param['strona']) ? $param['strona'] : 1;
		
		$settings = array();

			$settings = array(
					'condition' => array(
					'id_category' => array(isset($param['cat_id']) ? $param['cat_id'] : $param['id'])
					));

		$dalData = ProductVotesTypeDAL::GetDalDataObj($settings);
		$dalData->setCount(1);
		$obj = ProductVotesTypeDAL::GetResult($dalData);

		return $obj;
	}

	private function getCategoriesList($param) {

		$dalData = CategoryDAL::GetDalDataObj(
						array(
							'condition' => array(
							),
							'join' => array(
								'CategoryDescription' => ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = ' . Registry::Get('APPLICATION_LANGUAGE_ID') . ')',
							),
						)
		);

		return CategoryDAL::GetResult($dalData);
		
	}
	
	private function processEditVote($param) {

		try {
			$active = Request::Get('active');
			$o = Request::Get('overall');
			if(empty($o))
				$o = 0;
			
			if($active == 'on') {
				$active = 1;
			} else {
				$active = 0;
			}
			$voteType = new ProductVotesType(Request::Get('vid'), Request::Get('name'), $param['id'], $o, $active);
			
			ProductVotesTypeDAL::Save($voteType->GetDalDataObj());
		} catch (Exception $e) {
			
		}
	}

	public function VoteDeleteAction($param) {
		if (!isset($param['id'])) {
			return $this->AddRedirect(Router::GenerateUrl('LanguageIndex', array('Category' => 'Index')), 0);
		}

		$obj = ProductVotesTypeDAL::GetResult(
						ProductVotesTypeDAL::GetDalDataObj(
								array(
									'condition' => array(
										'id' => array($param['id'])
									)
								)
						)
		);

		if (!isset($obj[0])) {
			return $this->AddRedirect(Router::GenerateUrl('LanguageIndex', array('Category' => 'Index')), 0);
		}
		$obj = $obj[0];

		ProductVotesTypeDAL::DefaultDelete($obj->GetDalDataObj());
		$info = 'Typ oceny został usunięty';
		if(isset($param['redir'])) {
			return	$this->AddRedirect(Router::GenerateUrl('CategoryVotesss', array('Category' => 'Votes')), 0);	
		} else {
			return	$this->AddRedirect(Router::GenerateUrl('CategoryVoteIndex', array('Category' => 'VoteIndex', 'id' => $obj->getIdCategory())), 0);
		}
	}

	public function VotesAction($param) {
		$all = TRUE;
		$param['id'] = '';
		if (Request::IsPost()) {
			$all = FALSE;
			$param['cat_id'] = Request::Get('cat_id');
		}
		$arrVotes = $this->getVoteList($param, $all);
		$this->smarty->assign('currentCategory', Request::Get('cat_id'));
		$this->smarty->assign('arrayObjVotes', $arrVotes);
		$this->smarty->assign('c', $this->getVoteListCount($param));
		$this->smarty->assign('arrayObjCategories', $this->getCategoriesList($param));
	}

	/**
	 * Usuwanie Category'u
	 *
	 * @param array $param
	 */
	public function DeleteAction($param) {

		if (!isset($param['id'])) {
			return $this->AddRedirect(Router::GenerateUrl('LanguageIndex', array('Category' => 'Index')), 0);
		}

		$obj = CategoryDAL::GetResult(
						CategoryDAL::GetDalDataObj(
								array(
									'condition' => array(
										'id' => array($param['id'])
									)
								)
						)
		);
		if (!isset($obj[0])) {
			return $this->AddRedirect(Router::GenerateUrl('LanguageIndex', array('Category' => 'Index')), 0);
		}
		$obj = $obj[0];

		// subcategories
		$var = array(
			'subcategories' => 0,
			'products' => 0
		);
		if($obj->getParent() == 0)
		{
			$dalData = CategoryDAL::GetDalDataObj(array('condition'=>array('parent'=>$obj->getId())));
			$dalData -> setCount(True);
			$var['subcategories'] = CategoryDAL::GetResult($dalData);
		} else {
			$dalData = ProductDAL::GetDalDataObj(array('condition'=>array('id_category'=>$obj->getId())));
			$dalData -> setCount(True);
			$var['products'] = CategoryDAL::GetResult($dalData);
		}
		
		$all = array_sum($var);
		
		if($all == 0)
		{
			CategoryDAL::DefaultDelete($obj->GetDalDataObj());
			return $this->AddRedirect(Router::GenerateUrl('CategoryEdit', array('Category' => 'Index')), 0);
		} else {
			$this->smarty->assign('elementsCount', $var);
		}
		

	}
	public function ToggleOverallAction($param) {
		try {
		$this->SetAjaxRender();

		$dalObj = ProductVotesTypeDAL::GetDalDataObj(array('id' => $param['id']));
		$this->content = ProductVotesTypeDAL::DefaultToggleFieldById($dalObj, 'overall');
		} catch (Exception $e) {
			echo $e->getMessage();
		}
	}
	public function ToggleVoteActiveAction($param) {
		try {
		$this->SetAjaxRender();

		$dalObj = ProductVotesTypeDAL::GetDalDataObj(array('id' => $param['id']));
		$this->content = ProductVotesTypeDAL::DefaultToggleFieldById($dalObj, 'active');
		} catch (Exception $e) {
			echo $e->getMessage();
		}
	}
	public function ToggleStatusAction($param) {
		$this->SetAjaxRender();

		$dalObj = CategoryDAL::GetDalDataObj(array('id' => $param['id']));
		$this->content = CategoryDAL::DefaultToggleFieldById($dalObj, 'active');
	}

	public function AssignPreferenceAction($param) {
		
	}

	public function ValidateAdd() {
		$validator = new Validator(array_merge(Request::GetAllPost(), $_FILES));

		$validator->IsEmpty('name', 'Nazwa nie może być pusta.');
		$validator->IsEmpty('description', 'Opis nie może być pusty.');

		return $validator->GetErrorList();
	}

	public function ValidateEdit() {
		$validator = new Validator(array_merge(Request::GetAllPost(), $_FILES));

		$validator->IsEmpty('name', 'Nazwa nie może być pusta.');
		$validator->IsEmpty('description', 'Opis nie może być pusty.');

		return $validator->GetErrorList();
	}

	/**
	 * Wspolna metoda
	 *
	 */
	public function preDispatch($param) {
//		$this->AddScript('jquery-1.4.2.js');
		$this->Run($param);
		$this->RunShared('Auth', array());
	}

	public function postDispatch($param) {
		
	}

	public function SearchAction($param) {
		$searchString = null;

		if (Request::IsPost()) {
			$param['search'] = urlencode(Request::GetPost('search'));
		}

		$searchString = urldecode($param['search']);


		if (mb_strlen($searchString) < 4) {
			return $this->AddRedirectInfo('Podane wyrażenie jest za krótkie', null, Router::GenerateUrl('Category/Index', array('Category' => 'Index')));
		}


		$table_data = $this->getTableData('category_table', $param, array('o' => 'name', 'v' => 'malejaco', 't' => 10));
		$v = $table_data['v'] == 'malejaco' ? 'DESC' : 'ASC';
		$oTable = array(
			'name' => 'category_description.name',
			'description' => 'category_description.description'
		);
		$o = $oTable[$table_data['o']];
		$p = isset($param['strona']) ? $param['strona'] : 1;

		$dalData = CategoryDAL::GetDalDataObj(
						array(
							'count' => true,
							'condition' => array(
							//'parent'=> array('NULL'),
							),
							'join' => array(
								'CategoryDescription' => ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = ' . Registry::Get('APPLICATION_LANGUAGE_ID') . ')',
							),
						)
		);

		$dalData->addCondition('category_description.name', '\'%' . $searchString . '%\'', 'LIKE');

		$this->smarty->assign('c', CategoryDAL::getResult($dalData));

		$dalData->setCount(false);
		$dalData->setLimit((($p - 1) * $table_data['t']) . ', ' . $table_data['t']);

		$arrayObjCategories = CategoryDAL::GetResult($dalData);

		$this->smarty->assign('arrayObjCategories', $arrayObjCategories);
	}

}

?>